//输入一个链表，输出该链表中倒数第k个节点。为了符合大多数人的习惯，本题从1开始计数，即链表的尾节点是倒数第1个节点。 
//
// 例如，一个链表有 6 个节点，从头节点开始，它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。 
//
// 
//
// 示例： 
//
// 
//给定一个链表: 1->2->3->4->5, 和 k = 2.
//
//返回链表 4->5. 
//
// Related Topics 链表 双指针 👍 457 👎 0


package com.leetcode.editor.cn;

import com.leetcode.editor.cn.common.ListNode;

public class PJianZhiOffer22LianBiaoZhongDaoShuDiKgeJieDianLcof {
    public static void main(String[] args) {
        Solution solution = new PJianZhiOffer22LianBiaoZhongDaoShuDiKgeJieDianLcof().new Solution();
        ListNode head = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        head.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        solution.getKthFromEnd(head, 3);
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode getKthFromEnd(ListNode head, int k) {
            if (head == null || k <= 0) {
                return null;
            }
            int l = 0, n = k;
            ListNode tail = head, result = head;
            while (n >= 1) {
                if (tail == null) {
                    return null;
                }
                tail = tail.next;
                n--;
            }
            while (tail != null) {
                tail = tail.next;
                result = result.next;
            }
            return result;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}